package jm.data.structure.queue;

import org.omg.CORBA.PRIVATE_MEMBER;

/**
 * @Description 环形队列实现
 * @date 2022/4/8 9:20
 */
public class CircleQueue<E> {

    // 队列长度
    private int size;

    // 存储元素数组
    private E[] elements;

    // 存储队头下标
    private int front;

    // 默认容量
    private static final int DEFAULT_CAPACITY = 10;

    public CircleQueue(){
        elements = (E[]) new Object[DEFAULT_CAPACITY];
    }

    /**
     * 返回队列元素数量
     * @return
     */
    public int size(){
        return size;
    }

    /**
     * 判断队列是否为空
     * @return
     */
    public boolean isEmpty(){
        return size == 0;
    }

    /**
     * 入队
     * @param e
     */
    public void enQueue(E e){
        ensureCapacity(size + 1);
        elements[getIndex(size)] = e;
        size++;
    }

    /**
     * 出队
     * @return
     */
    public E deQueue(){
        E e = elements[front];
        elements[front] = null;
        front = getIndex(1);
        size--;
        return e;
    }

    /**
     * 查看队中最前方元素
     * @return
     */
    public E front(){
        return elements[front];
    }

    /**
     * 清空队列
     */
    public void clear(){
        for (int i = 0; i < elements.length; i++) {
            elements[getIndex(i)] = null;
        }
        size = 0;
        front = 0;
        elements = null;
    }

    private int getIndex(int index){
        index += front;
        return index - (index >= elements.length ? elements.length : 0);
    }

    /**
     * 保证要有capacity的容量
     * @param capacity
     */
    private void ensureCapacity(int capacity) {
        int oldCapacity = elements.length;
        if (oldCapacity >= capacity){
            return;
        }
        // 变成原先容量的 1.5 倍
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        E[] newElements = (E[]) new Object[capacity];
        for (int i = 0; i < size; i++) {
            newElements[i] = elements[(i + front) % elements.length];
        }
        elements = newElements;
        front = 0;
    }

}
